<template>
  <div class="article-detail-main">
    <el-card shadow="never" class="margin_30">
      <div slot="header">
        <span>{{ $route.query.id? '编辑':'新增' }}文章</span>
      </div>
      <!-- card body -->
      <el-form ref="articleForm" :model="article" :rules="rules" label-width="120px" :inline="false" size="mini">
        <el-row :gutter="20">
          <el-col :span="6" :offset="0">
            <el-form-item label="作者" prop="author">
              <el-input v-model="article.author" />
            </el-form-item>
          </el-col>
          <el-col :span="6" :offset="0">
            <el-form-item label="标题" prop="title">
              <el-input v-model="article.title" />
            </el-form-item>
          </el-col>
          <el-col :span="6" :offset="0">
            <el-form-item label="是否显示">
              <el-switch v-model="article.isShow" :active-value="1" :inactive-value="0" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="13" :offset="0">
            <el-form-item label="摘要">
              <el-input
                v-model="article.summary"
                type="textarea"
                placeholder="摘要"
                :rows="3"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12" :offset="0">
            <el-form-item label="封面图片">
              <el-upload
                ref="clearUpload"
                class="upload-demo"
                :action="uploadFileOss"
                :headers="token"
                :on-success="coverImgUploadSucc"
                :before-upload="beforeCoverImgUpload"
              >
                <img v-if="article.coverImg" style="width:100px;height:100px" :src="article.coverImg" alt="">
                <el-button v-else size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12" :offset="0">
            <el-form-item label="切换富文本类型">
              <el-radio v-model="article.editorType" :label="0" @change="editTypeChange">富文本</el-radio>
              <el-radio v-model="article.editorType" :label="1" @change="editTypeChange">markdown</el-radio>
              <span style="color:#e6a23c"><i class="el-icon-warning-outline" /> 注意!切换编辑器会清空编辑内容</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24" :offset="0">
            <Tinymce v-if="article.editorType == 0" v-model="article.content1" />
            <mavon-editor v-if="article.editorType == 1" ref="mdEdit" v-model="article.content1" @imgAdd="$imgAdd" />
          </el-col>
        </el-row>
        <el-row :gutter="20" type="flex" justify="center" style="margin-top:20px">
          <el-col :span="6" :offset="0">
            <el-form-item>
              <el-button type="primary" @click="addNow">立即{{ $route.query.id? '修改':'新增' }}</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

  </div>
</template>

<script>
import Tinymce from '@/components/Tinymce'
import mix from '@/mixins'
import axios from 'axios'
import { addArticle, productArticle, updateArticle } from '@/api/content/article'
export default {
  components: {
    Tinymce
  },
  mixins: [mix],
  data() {
    return {
      rules: {
        author: [
          { required: true, message: '请输入作者名称', trigger: 'blur' },
          { min: 2, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        title: [{ required: true, message: '请输入文章标题', trigger: 'blur' }]
      },
      article: {
        editorType: 0,
        coverImg: ''
      }
    }
  },

  created() {
    if (this.$route.query.id) {
      productArticle(this.$route.query.id)
        .then(res => {
          console.log(res)
          this.article = res.data.productArticle
        })
    }
  },

  mounted() {

  },

  methods: {
    // markdown上传图片 绑定@imgAdd event
    $imgAdd(pos, $file) {
      // 第一步.将图片上传到服务器.
      var formdata = new FormData()
      formdata.append('file', $file)
      axios({
        url: this.uploadFileOss,
        method: 'post',
        data: formdata,
        headers: this.token
      }).then((res) => {
        // 第二步.将返回的url替换到文本原位置![...](0) -> ![...](url)
        /**
               * $vm 指为mavonEditor实例，可以通过如下两种方式获取
               * 1. 通过引入对象获取: `import {mavonEditor} from ...` 等方式引入后，`$vm`为`mavonEditor`
               * 2. 通过$refs获取: html声明ref : `<mavon-editor ref=md ></mavon-editor>，`$vm`为 `this.$refs.md`
               */
        if (res.data.success) {
          this.$refs.mdEdit.$img2Url(pos, res.data.data.fileUrl)
        } else {
          this.$message.error(res.data.message)
        }
      })
    },
    // 编辑类型发生变化
    editTypeChange() {
      this.article.content1 = ''
    },
    // 封面图片上传之前校验
    beforeCoverImgUpload(file) {
      // const isJPG = file.type === 'image/jpeg' | file.type === 'image/png' | file.type === 'image/gif' | file.type === 'image/webp'
      const reg = /^image\/(jpeg|png|gif|webp)$/
      const isImg = reg.test(file.type)
      const isLt1dot5M = file.size / 1024 / 1024 < 1.5

      if (!isImg) {
        this.$message.error('上传图片只能是 jpeg|png|gif|webp 格式!')
      }
      if (!isLt1dot5M) {
        this.$message.error('上传图片大小不能超过 1.5MB!')
      }
      return isImg && isLt1dot5M
    },
    // 封面图片上传成功
    coverImgUploadSucc(response) {
      // console.log(response)
      if (response.success) {
        this.article.coverImg = response.data.fileUrl
        // 清空已上传的文件列表
        this.$refs.clearUpload.clearFiles()
      } else {
        this.$message.error(response.message)
      }
    },
    addNow() {
      this.$refs.articleForm.validate((valid) => {
        if (valid) {
          if (this.article.editorType === 0) { // 富文本
            // 富文本转换后的HTML和原文一样
            this.article.content2 = this.article.content1
          } else if (this.article.editorType === 1) {
            // 获取markdown转换后的html文档
            this.article.content2 = this.$refs.mdEdit.d_render
          }
          console.log(this.article)
          // 校验成功
          if (this.$route.query.id) {
            // 修改文章
            updateArticle(this.article)
              .then(res => {
              // console.log(res)
                if (res.success) {
                  this.$router.push({ name: 'contentArticle' })
                } else {
                  this.$message.error(res.message)
                }
              })
          } else {
            // 新增文章
            addArticle(this.article)
              .then(res => {
              // console.log(res)
                if (res.success) {
                  this.$router.push({ name: 'contentArticle' })
                } else {
                  this.$message.error(res.message)
                }
              })
          }
        } else {
          // console.log('error submit!!')
          this.$message.error('请注意表单验证')
          return false
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
